import { getToken, setToken, removeToken } from '@/utils/auth'
import { login, getUserInfo } from '@/api/user'
const state = {
  token: getToken() || null,// 读取缓存的token
  userInfo: {}// getters里面访问数据为null则会报错
}
const mutations = {
  setToken(state, token) {
    state.token = token.data.token // 将token传递给vuex
    setToken(token.data.token) // 同步给缓存
  },
  removeToken(state) {
    state.token = null,// 将token置空
      removeToken()
  },
  setUserInfo(state, result) {// 获取用户信息
    state.userInfo = { ...result.data }//响应式
  },
  removeUserInfo(state) {
    state.userInfo = {}
  }
}
const actions = {
  async login(context, data) {
    const res = await login(data)
    context.commit('setToken', res)

  },
  async getUserInfo(context) {//网络请求用户名
    const result = await getUserInfo()
    context.commit('setUserInfo', { ...result })
    return result
  },
  logout(context) {
    context.commit('removeToken')
    context.commit('removeUserInfo')

  }
}
export default {
  namespaced: true,
  state,
  mutations,
  actions
}
